﻿using Furion.CMS.Application.Dto;
using Furion.CMS.Core.Permission;
using Furion.CMS.Domain;
using Mapster;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Furion.CMS.Application
{
    public class PermissionProfile : IRegister
    {
        public void Register(TypeAdapterConfig config)
        {
            config.ForType<PermissionInfo, PermissionDto>()
                .Map(dest => dest.DependentResources, src => src.DependentResources.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Split(new string[] { "_" }, StringSplitOptions.RemoveEmptyEntries)), src => !string.IsNullOrWhiteSpace(src.DependentResources));

            config.ForType<KeyValuePair<string, string>, PermissionDto>()
                .ConstructUsing(src => new PermissionDto(src.Key, src.Value));

            config.ForType<PermissionDto, PermissionInfo>()
                .Map(dest => dest.DependentResources, src => string.Join(",", src.DependentResources.Select(s => string.Join("_", s))));

            config.ForType<PermissionInfo, PermissionConfigDto>()
                .Map(dest => dest.PageFunctions, src => src.Children.Where(t => t.Type == PermissionType.Operate));

            config.ForType<PermissionConfigDto, PermissionInfo>()
                .Map(dest => dest.Children, src => src.PageFunctions.Adapt<List<PermissionInfo>>());

            config.ForType<PermissionConfigReleaseDto, PermissionInfo>()
                .Inherits<PermissionConfigDto, PermissionInfo>();

            config.ForType<PermissionInfo, PermissionOptionsDto>()
                .Map(dest => dest.Children, src => src.Children.Where(t => t.Type != PermissionType.Operate), s => s.Children.Any())
                .Map(dest => dest.OperateList, src => src.Children.Where(t => t.Type == PermissionType.Operate), s => s.Children.Any())
                .AfterMapping((src, dest) =>
                {
                    if (!(dest.Children?.Any() ?? false))
                    {
                        dest.Children = null;
                    }
                });

            config.ForType<PermissionGroupDefinition, PermissionOptionsDto>()
                .Map(dest => dest.Code, src => src.Name)
                .Map(dest => dest.Name, src => src.DisplayName)
                .Map(dest => dest.Children, src => src.Permissions.Values.Where(t => t.IsEnabled));

            config.ForType<PermissionDefinition, PermissionOptionsDto>()
                .Map(dest => dest.Name, src => src.DisplayName)
                .Map(dest => dest.Code, src => src.Name);

        }
    }
}
